﻿#include "tomatoclockfragment.h"
#include "ui_tomatoclockfragment.h"
#include <QMessageBox>
void TomatoClockFragment::onTimerTimeout() {
    secondsRest--;
    ui->label_time->setText(QString::number(secondsRest/60)+":"+QString::number(secondsRest%60));
    if(secondsRest<=0) {
        this->currentMode^=1;
        if(currentMode==MODE_WORK) {
            secondsRest = workSec;
            ui->label_state->setText(tr("Work mode"));
            tts.say(tr("It's work time now!"));
            ui->label_time->setText(QString::number(secondsRest/60)+":"+QString::number(secondsRest%60));
        } else {
            secondsRest = restSec;
            ui->label_state->setText(tr("Rest mode"));
            tts.say(tr("It's rest time now!"));
            ui->label_time->setText(QString::number(secondsRest/60)+":"+QString::number(secondsRest%60));
        }

    }
}

TomatoClockFragment::TomatoClockFragment(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TomatoClockFragment) {
    ui->setupUi(this);
    this->paused = false;
    connect(&timer,&QTimer::timeout,this,&TomatoClockFragment::onTimerTimeout);
    this->secondsRest = this->workSec = this->restSec = 0;
}

TomatoClockFragment::~TomatoClockFragment() {
    delete ui;
}

void TomatoClockFragment::on_pushButton_start_clicked() {
    if(this->paused) {
        ui->pushButton_start->setEnabled(false);
        ui->pushButton_stop->setEnabled(true);
        ui->pushButton_reset->setEnabled(true);
        this->timer.start();
        return;
    }
    this->workSec = ui->spinBox_workMinute->value()*60+ui->spinBox_workSecond->value();
    this->restSec = ui->spinBox_restMinute->value()*60+ui->spinBox_restSecond->value();
    if(this->workSec==0) {
        QMessageBox::warning(this,tr("Error"),tr("Error!Work time can't be zero\nDiligence is a natural magnet that attracts all good things."));
        return;
    }
    if(this->restSec==0) {
        QMessageBox::warning(this,tr("Error"),tr("Error!Rest time can't be zero\nAll work no play makes Jack a dull boy"));
        return;
    }
    this->timer.setInterval(1000);
    this->secondsRest = workSec;
    this->currentMode = MODE_WORK;
    ui->label_time->setText(QString::number(secondsRest/60)+":"+QString::number(secondsRest%60));

    this->timer.start();
    ui->pushButton_start->setEnabled(false);
    ui->pushButton_stop->setEnabled(true);
}


void TomatoClockFragment::on_pushButton_stop_clicked() {
    this->timer.stop();
    this->paused = true;
    ui->pushButton_start->setEnabled(true);
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_reset->setEnabled(true);
}


void TomatoClockFragment::on_pushButton_reset_clicked() {
    this->paused = false;
    this->currentMode = MODE_WORK;
    ui->label_state->setText(tr("Work mode"));
    ui->label_time->setText("0:0");
    this->timer.setInterval(1000);
}

